package org.gpslw.service;

import org.geotools.api.data.FeatureReader;
import org.geotools.api.data.FeatureWriter;
import org.geotools.api.data.Transaction;
import org.geotools.api.feature.simple.SimpleFeature;
import org.geotools.api.feature.simple.SimpleFeatureType;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.store.ContentFeatureCollection;
import org.geotools.data.store.ContentFeatureSource;
import org.geotools.jdbc.JDBCDataStore;
import org.gpslw.entity.NycNeighborhoods;
import org.gpslw.util.SimpleFeatureUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class NycNeighborHoodsService {

    @Autowired
    private JDBCDataStore jdbcDataStore;

    public List<NycNeighborhoods> findAll() {
        try {
            ContentFeatureCollection features = jdbcDataStore.getFeatureSource(NycNeighborhoods.FEATURE_TYPE_NAME).getFeatures();
            SimpleFeatureIterator featureIterator = features.features();
            List<NycNeighborhoods> result = new ArrayList<>();
            while (featureIterator.hasNext()) {
                SimpleFeature feature = featureIterator.next();
                NycNeighborhoods nycNeighborhoods = SimpleFeatureUtils.toBean(feature, NycNeighborhoods.class);
                result.add(nycNeighborhoods);
            }
            featureIterator.close();
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void save(){
        NycNeighborhoods nycNeighborhoods = new NycNeighborhoods();
        nycNeighborhoods.setBoroname("test_wf");
        nycNeighborhoods.setName("test_wf");
        try {
            SimpleFeatureType simpleFeatureType = jdbcDataStore.getSchema(NycNeighborhoods.FEATURE_TYPE_NAME);
            SimpleFeature simpleFeature = SimpleFeatureUtils.toSimpleFeature(nycNeighborhoods, simpleFeatureType);
            //保存的方法比较奇怪，该方法是源自底层FeatureWriter，不仅仅对应数据库，还对应其他数据源。
            FeatureWriter<SimpleFeatureType, SimpleFeature> featureWriter = jdbcDataStore.getFeatureWriterAppend(NycNeighborhoods.FEATURE_TYPE_NAME, Transaction.AUTO_COMMIT);
            SimpleFeature waitToWriteFeature = featureWriter.next();
            waitToWriteFeature.setAttributes(simpleFeature.getAttributes());
            featureWriter.write();
            featureWriter.close();
        } catch (IOException e) {

        }
    }
}
